package com.zx.service.order.impl;

import com.zx.config.exception.BaseBusinessException;
import com.zx.config.exception.BizError;
import com.zx.dao.goods.GoodsImgMapper;
import com.zx.dao.goods.GoodsMapper;
import com.zx.dao.order.OrderDetailsMapper;
import com.zx.dao.order.OrderMapper;
import com.zx.dao.order.StateMapper;
import com.zx.dao.shop.ShoppingCartMapper;
import com.zx.dao.user.ReceivingMapper;
import com.zx.dto.request.order.OrderAddDtoReq;
import com.zx.dto.request.order.OrderDtoRequest;
import com.zx.dto.response.goods.GoodsDetailDto;
import com.zx.dto.response.goods.GoodsImgDto;
import com.zx.enums.GoodsImgTypeEnums;
import com.zx.enums.OrderEnums;
import com.zx.model.user.User;
import com.zx.service.order.OrderService;
import com.zx.util.CookieUtil;
import com.zx.util.MallConstant;
import com.zx.util.Uuid;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sunkai
 * @date 2022/8/21 0021 19:20
 * @mood zhou xun
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private StateMapper stateMapper;
    @Autowired
    private GoodsImgMapper goodsImgMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addOrder(OrderAddDtoReq orderAddDtoReqs, String userToken) {
        Map<Integer, Integer> goodsMap = orderAddDtoReqs.getGoodsMap();
        Date date = new Date();
        if (userToken != null) {
            User user = MallConstant.MAP.get(userToken);
            List<Integer> integers = Arrays.asList(orderAddDtoReqs.getGoodsMap().keySet().toArray(new Integer[0]));
            OrderDtoRequest orderDtoRequest = new OrderDtoRequest();
            List<GoodsImgDto> goodsImgDtoList = goodsImgMapper.queryList(integers, GoodsImgTypeEnums.COVER.getType());
            orderDtoRequest.setGoodsIdList(integers);
            orderDtoRequest.setReceivingId(orderAddDtoReqs.getAddreId());
            List<GoodsDetailDto> goodsDetailDtos = goodsMapper.goodShop(orderDtoRequest);
            List<OrderDtoRequest> orderDtoRequestList = new ArrayList<>();

            for (int i = 0; i < goodsDetailDtos.size(); i++) {
                OrderDtoRequest orderDtoRequests = new OrderDtoRequest();
                String goodsString = goodsDetailDtos.get(i).getGoodId();
                orderDtoRequests.setGoodsIdList(Arrays.stream(goodsString.split(",")).map(goodsIds -> {
                    return Integer.valueOf(goodsIds);
                }).collect(Collectors.toList()));
                orderDtoRequests.setGoodsQuantity(goodsMap.get(goodsDetailDtos.get(i).getId()));
                orderDtoRequests.setOrderId(Integer.parseInt(Uuid.getGUID()));
                orderDtoRequests.setShopId(goodsDetailDtos.get(i).getShopId());
                orderDtoRequests.setShopName(goodsDetailDtos.get(i).getShopName());
                orderDtoRequests.setFreight(new BigDecimal(String.valueOf(orderAddDtoReqs.getFreight())));
                orderDtoRequests.setTotalAmount(new BigDecimal(goodsDetailDtos.get(i).getPrice() * orderAddDtoReqs.getGoodsMap().get(goodsDetailDtos.get(i).getId())));
                orderDtoRequests.setUserId(user.getId());
                orderDtoRequests.setPayAmount(new BigDecimal(goodsDetailDtos.get(i).getPrice() * orderAddDtoReqs.getGoodsMap().get(goodsDetailDtos.get(i).getId())));
                orderDtoRequests.setGoodsImg(goodsImgDtoList.get(i).getGoodsImg());
                orderDtoRequests.setGoodsName(goodsDetailDtos.get(i).getProductName());
                orderDtoRequests.setCreateTime(date);
                orderDtoRequests.setUpdateTime(date);
                orderDtoRequests.setShopId(goodsDetailDtos.get(i).getShopId());
                orderDtoRequests.setPayType(OrderEnums.STATE_WECHATPAY_ENUM.getStateType());
                orderDtoRequests.setPhone(goodsDetailDtos.get(i).getPhone());
                orderDtoRequests.setReceivingName(goodsDetailDtos.get(i).getReceivingName());
                orderDtoRequests.setDeliveryAddress(goodsDetailDtos.get(i).getDeliveryAddress());
                orderDtoRequests.setStat(OrderEnums.STATE_ODLIGATION_ENUM.getStateType());
                orderDtoRequestList.add(orderDtoRequests);
            }
            //订单
            int i = orderMapper.addOrder(orderDtoRequestList);
            if (i <= 0) {
                throw new BaseBusinessException(BizError.ORDER_ERROR.getErrorMessage(), BizError.ORDER_ERROR.getErrorCode());
            }
            // 订单地址
            int i1 = orderMapper.addOrderAddress(orderDtoRequestList);
            if (i1 <= 0) {
                throw new BaseBusinessException(BizError.ORDER_ADDRESS_ERROR.getErrorCode(), BizError.ORDER_ADDRESS_ERROR.getErrorMessage());
            }
            // 订单状态
            int i2 = stateMapper.addState(orderDtoRequestList);
            if (i2 <= 0) {
                throw new BaseBusinessException(BizError.ORDER_JOURNAL_ERROR.getErrorCode(), BizError.ORDER_JOURNAL_ERROR.getErrorMessage());
            }
            List<OrderDtoRequest> orderDetailDtoList = new ArrayList<>();
            for (OrderDtoRequest dtoRequest : orderDtoRequestList) {
                for (Integer goodIds : dtoRequest.getGoodsIdList()) {
                    OrderDtoRequest detail = new OrderDtoRequest();
                    BeanUtils.copyProperties(dtoRequest, detail);
                    detail.setGoodsId(goodIds);
                    detail.setGoodsQuantity(dtoRequest.getGoodsQuantity());
                    orderDetailDtoList.add(detail);
                }
            }
            // 订单明细
            int i3 = orderDetailsMapper.addOrderDetails(orderDetailDtoList);
            if (i3 <= 0) {
                throw new BaseBusinessException(BizError.ORDER_DETAILS_ERROR.getErrorCode(), BizError.ORDER_DETAILS_ERROR.getErrorMessage());
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateOrderDetails(String userToken,OrderDtoRequest orderDtoRequest) {
        Date date=new Date();
        User user = MallConstant.MAP.get(userToken);
        orderDtoRequest.setUpdateTime(date);
        orderDtoRequest.setUserId(user.getId());
        orderDtoRequest.setStat(OrderEnums.STATE_DROPSHIP_ENUM.getStateType());
        //订单状态
        int i = orderMapper.updateOrderDetails(orderDtoRequest);
        if (i<=0){
            throw new BaseBusinessException(BizError.ORDER_STATE_ERROR.getErrorCode(),BizError.ORDER_STATE_ERROR.getErrorMessage());
        }
        List<OrderDtoRequest> orderDtoRequestList=new ArrayList<>();
        orderDtoRequest.setCreateTime(date);
        orderDtoRequestList.add(orderDtoRequest);
        //
        int i1 = stateMapper.addState(orderDtoRequestList);
        if (i1<=0){
            throw new BaseBusinessException(BizError.ORDER_JOURNAL_ERROR.getErrorCode(),BizError.ORDER_JOURNAL_ERROR.getErrorMessage());
        }
        return true;
    }

}
